<template>
  <div class="chat-container">
    <Search></Search>
    <ChatList :chatList="chatList"></ChatList>
    <ChatPanel :chatData="currentChat" :messages="currentMessageList"></ChatPanel>
  </div>
</template>

<script>
  import { ChatList, ChatPanel, Search } from './components'
  import { getUserChat } from '../../api/api'
  import { defaultChatList } from '../../api/chat'
  import ChatController from '../../socket/chatController'

  export default {
    components: {
      ChatList,
      ChatPanel,
      Search
    },
    data() {
      return {
        chatList: defaultChatList,
        currentChat: defaultChatList[0],
        currentMessageList: []
      }
    },
    mounted() {
      const that = this
      this.$bus.$on('change-user-panel', function(chat) {
        // 切换用户，需要更新currentChat和currentMessageList
        that.currentChat = chat
        that.getMessage()
      })
      this.$bus.$on('send-message', function(sendMessage) {
        // 发送给服务器消息，这里要更新store中的存储
        // 同时更新currentMessageList的值
        const message = {
          own: true,
          image: 'static/avatar/own.jpg',
          type: 'text',
          content: sendMessage.content,
          datetime: '18/12/12'
        }
        that.setMessage(message)
      })
      this.$bus.$on('receive-message', function(receiveMessage) {
        // 接收到服务器发送来的消息，这里要更新store中的存储
        // 同时更新currentMessageList的值
        const message = {
          own: false,
          image: 'static/avatar/other.jpg',
          type: 'text',
          content: receiveMessage.content,
          datetime: '18/12/12'
        }
        that.setMessage(message)
      })
    },
    created() {
      const userInfo = this.$db.read().get('user').value()
      const userId = userInfo.userId
      if (userId) {
        this.getUserChat(userId)
        // 初始化WebSocket连接操作
        ChatController.init()
        this.getMessage()
      }
    },
    beforeDestroy() {
      this.$bus.$off('change-user-panel')
      this.$bus.$off('send-message')
      this.$bus.$off('receive-message')
    },
    methods: {
      setMessage(message) {
        if (this.currentMessageList.length >= 500) {
          for (let i = 0; i < 500; i++) {
            this.currentMessageList[i] = this.currentMessageList[i + 1]
          }
          this.currentMessageList[500] = message
        } else {
          this.currentMessageList.push(message)
        }
      },
      getMessage() {
        // 初始化当前用户的消息内容
        const that = this
        this.$store.dispatch('GetMessageListByUser', this.currentChat.id).then(messages => {
          that.currentMessageList = messages
        })
      },
      getUserChat(userId) {
        const params = { userId: userId }
        getUserChat(params).then(response => {
          this.chatList = defaultChatList.concat(response.data)
        })
      }
    }
  }
</script>


